package main

import (
	"context"
	"errors"
	"fmt"
	"google.golang.org/grpc"
	"mygrpc/message"
	"net"
	"time"
)

/**
grpc:是google公司基于RPC开发的远程过程调用框架，该框架包含各语言版本实现
grpc-go:是grpc的go语言版本实现
下载：go get -u google.golang.org/grpc 具体使用可以到其github主页examples文件夹下看其使用示列
编译.proto文件： protoc --go_out=plugins=grpc:. message.proto
 */

type OrderServer struct {

}

func (this *OrderServer)GetOrderInfo(ctx context.Context,req *message.OrderReq)(*message.OrderInfo,error){
	orderMaps := map[string]message.OrderInfo{
		"001":{OrderId:"001",OrderName:"可口可乐",OrderStatus:"待发货"},
		"002":{OrderId:"002",OrderName:"雪碧",OrderStatus:"已发货"},
		"003":{OrderId:"003",OrderName:"冰红茶",OrderStatus:"待收货"},
	}
	nowTimeStamp := time.Now().Unix()
	if req.TimeStamp > nowTimeStamp{
		return nil,errors.New("time error")
	}
	order := orderMaps[req.OrderId]
	if order.OrderId!=""{
		return &message.OrderInfo{OrderId:order.OrderId,OrderName:order.OrderName,OrderStatus:order.OrderStatus},nil
	}else {
		return nil,errors.New("order not exist")
	}
}

func main(){
	listen,err := net.Listen("tcp",":8081")
	fmt.Println("服务启动成功...")
	if err!=nil{
		panic(err.Error())
	}
	//创建一个grpc服务
	s := grpc.NewServer()
	//注册服务
	message.RegisterOrderServerServer(s,&OrderServer{})

	err = s.Serve(listen)
	if err != nil {
		panic(err)
	}
}
